import { defineStore } from 'pinia';

// 定义用户状态类型
interface UserState {
  name: string
  token: string
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    name: '',
    token: ''
  }),
  getters: {
    // 获取用户全名
    fullName: (state) => `Mr/Ms ${state.name}`,
    // 是否已登录
    isLoggedIn: (state) => !!state.token
  },
  actions: {
    // 登录操作
    async login(username: string, password: string) {
      // 模拟API调用
      const response = await fakeLoginApi(username, password)
      this.token = response.token
      this.name = response.name
    },
    // 登出操作
    logout() {
      this.$reset()
    }
  },
  // persist: {
  //   key: 'user-store', // 存储的 key
  //   storage: localStorage, // 指定存储方式
  //   paths: ['name', 'token'] // 只持久化这些字段
  // }
})

// 模拟API
async function fakeLoginApi(username: string, password: string) {
  return new Promise<{ token: string; name: string }>((resolve) => {
    setTimeout(() => {
      resolve({
        token: 'xxx-6688',
        name: username
      })
    }, 500)
  })
}